package com.jiexin.service;

import com.google.common.base.Preconditions;
import com.jiexin.common.RequestHolder;
import com.jiexin.dao.PlmWorkFlowMapper;
import com.jiexin.dao.PlmWorkFlowStatusMapper;
import com.jiexin.exception.ParamException;
import com.jiexin.model.PlmWorkFlow;
import com.jiexin.param.WorkFlowParam;
import com.jiexin.util.BeanValidator;
import com.jiexin.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 15:15 2018/5/18 0018
 * @Modified By:
 */
@Service
public class PlmWorkFlowService {

    @Resource
    PlmWorkFlowMapper plmWorkFlowMapper;

    @Resource
    PlmWorkFlowStatusMapper plmWorkFlowStatusMapper;

    public void save(WorkFlowParam param) {
        BeanValidator.check(param);
        if(checkIsExist(param.getName(), param.getId())){
            throw new ParamException("不允许存在相同工作流名称");
        }
        PlmWorkFlow workFlow = PlmWorkFlow.builder().name(param.getName()).status(param.getStatus())
                .remark(param.getRemark()).build();
        workFlow.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        workFlow.setOperateTime(new Date());
        workFlow.setOperator(RequestHolder.getCurrentUser().getUsername());
        plmWorkFlowMapper.insertSelective(workFlow);
    }

    public void update(WorkFlowParam param) {
        BeanValidator.check(param);
        if(checkIsExist(param.getName(), param.getId())) {
            throw new ParamException("不允许存在相同工作流名称");
        }
        PlmWorkFlow before = plmWorkFlowMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的工作流不存在");
        PlmWorkFlow after = PlmWorkFlow.builder().id(param.getId()).name(param.getName()).status(param.getStatus())
                .remark(param.getRemark()).build();
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        plmWorkFlowMapper.updateByPrimaryKeySelective(after);
    }

    //检查是否存在相同名称的工作流
    private boolean checkIsExist(String name, Integer id) {
        return plmWorkFlowMapper.countByNameAndWorkFlowId(name, id) > 0;
    }

    //获取所有的workFlow
    public List<PlmWorkFlow> getAllWorkFlow() {
        return plmWorkFlowMapper.getAllWorkFlow();
    }

    public void delete(int workFlowId) {
        PlmWorkFlow plmWorkFlow = plmWorkFlowMapper.selectByPrimaryKey(workFlowId);
        Preconditions.checkNotNull(plmWorkFlow, "待删除的工作流不存在");
        if (plmWorkFlowStatusMapper.countByWorkFlowId(workFlowId) > 0){
            throw new ParamException("无法删除存在关卡条件的工作流");
        }
        plmWorkFlowMapper.deleteByPrimaryKey(workFlowId);
    }
}
